package com.eco.fanliapp.admin.controller.web;


import com.alibaba.fastjson.JSON;
import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppCompanyMapper;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGeneralFeeScheme;
import com.eco.fanliapp.entity.AppOrderFeeScheme;
import com.eco.fanliapp.entity.TaobaoScheme;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.SearchController;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.utils.MapValueHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.api.response.TbkScInvitecodeGetResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
public class AppCompanyController extends BaseController {

    @Autowired
    private IAppCompanyService companyService;

    @Autowired
    private AppCompanyMapper appCompanyMapper;

    @Autowired
    private TaoBaoPlanService taoBaoPlanService;

    @Autowired
    private IAppGeneralfeeschemeService generalfeeschemeService;

    @Autowired
    private IAppOrderfeeschemeService appOrderfeeschemeService;

    @Autowired
    private IAppCompanyService iAppCompanyService;

    @Autowired
    private SearchController searchController;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private ITaobaoSchemeService iTaobaoSchemeService;
    @Autowired
    private IDwzService dwzService;


    /**
     * 公司设置列表
     * @param params
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "/web/find/commpany/list")
    public ServerResponse<PageInfo> findCommpanyFourALL(@RequestParam HashMap<String,Object> params){
        MapValueHelper mapValueHelper = new MapValueHelper(params);
        int type = mapValueHelper.getInt("type");
        if(type == 0){
            params.remove("type");
        }
        if(getAuthentication().getRoleId() != 0){
            params.put("companyId",getAuthentication().getCompanyId());
        }
        return  companyService.findCommpanyFourALL(params);
    }
    @RequestMapping(method = RequestMethod.GET,value = "/web/find/commpany")
    public ServerResponse<PageInfo> findCommpany(@RequestParam HashMap<String,Object> params){
        MapValueHelper mapValueHelper = new MapValueHelper(params);
        int companyId = mapValueHelper.getInt("companyId");
        if(companyId == 0){
            return  ServerResponse.createByError();
        }
        return  companyService.findCommpany(params);
    }

    @RequestMapping(method = RequestMethod.GET,value = "/companys/all/list")
    public List<AppCompany> findCompanys(@RequestParam(required = false)  Integer companyType){
        return companyService.findCompanys(companyType);
    }


    /**
     * 添加分公司
     */
    @SysLogAnnotation(value = "添加分公司",userType = 2)
    @RequestMapping(method = RequestMethod.POST,value = "/web/find/commpany/insertAppCompany")
    public ServerResponse insertAppCompany(@RequestBody AppCompany appCompany){
        int i = companyService.insertAppCompany(appCompany);
        if(i>0){
            return ServerResponse.createBySuccess("保存成功");
        }else {
            return ServerResponse.createByErrorMessage("保存失败");
        }

    }


    /**
     * 配置
     */
    @SysLogAnnotation(value = "公司配置",userType = 2)
    @RequestMapping(method = RequestMethod.POST,value = "/web/find/commpany/save")
    public ServerResponse updateCommpanyFour(@RequestBody HashMap<String,Object> params){

        MapValueHelper mapValueHelper = new MapValueHelper(params);
        HashMap<String,Object> hashMap = new HashMap<String,Object>();
        int companyId = mapValueHelper.getInt("companyId");
        hashMap.put("compayName",mapValueHelper.getString("compayName"));
//        Integer taobaoscheme = null;//修改之前的taobaoscheme（用于判断是否修改了淘宝联盟）
        //添加
        if(companyId == 0){
            int num = companyService.findCommpanyFourALL(hashMap).getData().getList().size();
            if(num > 0){
                return ServerResponse.createByErrorMessage("公司名称重名，请重新输入");
            }
        }else {//修改
            hashMap.put("companyId",companyId);
//            List<AppCompany> list = companyService.findCommpanyFourALL(hashMap).getData().getList();
//            taobaoscheme = list.get(0).getTaoBaoScheme().getId();
            int num = companyService.findCommpanyFourALL(hashMap).getData().getList().size();
            if(num <=0 ){
                hashMap.remove("companyId");
                int num1 = companyService.findCommpanyFourALL(hashMap).getData().getList().size();
                if(num1 > 0){
                    return ServerResponse.createByErrorMessage("公司名称重名，请重新输入");
                }
            }
        }
        int taoBaoSchemeId = mapValueHelper.getInt("taoBaoScheme");
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("id",taoBaoSchemeId);
        TaobaoScheme taobaoScheme = taoBaoPlanService.findTaoBaoPlanAll(map).get(0);

        try{

//            String s = ApiUtils.postEcoData(ApiEnum.TAOBAO_TBK_CINVITECODE, "session="+taobaoScheme.getAppSession());
            String s = "";
            TbkScInvitecodeGetResponse tbkScInvitecodeGetResponse = searchController.tbkScInvitecode(taobaoScheme.getAppSession());
            if (tbkScInvitecodeGetResponse != null) {
                s = JSON.toJSONString(tbkScInvitecodeGetResponse);
            }

            TbkScInvitecodeGetResponse response = JsonUtils.getJsonToBean(s,TbkScInvitecodeGetResponse.class);
            response.getData().getInviterCode();
            params.put("inviteCode",response.getData().getInviterCode());
        } catch (Exception e) {

        }

        //获取会员邀请码
        try {
//            String sMember = ApiUtils.postEcoData(ApiEnum.TAOBAO_TBK_MINVITECODE, "session="+taobaoScheme.getAppSession());
            String sMember = "";
            TbkScInvitecodeGetResponse tbkScInvitecodeGetResponse = searchController.tbkMeInvitecode(taobaoScheme.getAppSession());
            if (tbkScInvitecodeGetResponse != null) {
                sMember = JSON.toJSONString(tbkScInvitecodeGetResponse);
            }

            TbkScInvitecodeGetResponse responseMember = JsonUtils.getJsonToBean(sMember,TbkScInvitecodeGetResponse.class);
            responseMember.getData().getInviterCode();
            params.put("minviteCode",responseMember.getData().getInviterCode());
        } catch (Exception e) {

        }

        //联盟推广位
        String generalizePid = mapValueHelper.getString("generalizePid");
        TaobaoScheme taobaoScheme_one = new TaobaoScheme();
        taobaoScheme_one.setGeneralizePid(generalizePid);
        taobaoScheme_one.setId(taoBaoSchemeId);
        iTaobaoSchemeService.updateTaobaoScheme(taobaoScheme_one);
        //刷新redis
        iTaobaoSchemeService.selectTaobaoSchemeById(taobaoScheme_one.getId(), 0);

        String siteNames[] = null;
        if (StringUtils.isNotEmpty(generalizePid)) {
            siteNames = generalizePid.split("_");
        }
        if (siteNames == null||siteNames.length != 4) {
            return ServerResponse.createByErrorMessage("推广位格式错误,请按照正确格式输入");
        }
        int i;
        if(companyId == 0){
            int size = appCompanyMapper.findCommpanyFourALL(null).size();
            if(size >0){
                params.put("type",2);
            }else {
                params.put("type",1);
            }
            i = companyService.insert(params);
        }else {
            //更换联盟，重置用户（淘宝用户ID，淘宝开放平台ID，渠道ID，会员ID,用户是否淘宝授权）
//            if(taoBaoSchemeId != taobaoscheme){
//                String inviteCode = (String) params.get("inviteCode");
//                String minviteCode = (String) params.get("minviteCode");
//                int i1 = appUserService.updateBatchByCompanyId(inviteCode,minviteCode,companyId);
//            }
            i = companyService.updateCommpanyFour(params);
            //刷新redis
            companyService.findtAppCompany(companyId, 0);
        }
        if(i>0){
           return ServerResponse.createBySuccess("保存成功");
        }else {
            return ServerResponse.createByErrorMessage("保存失败");
        }

    }

    /**
     * 修改类型  总公司  分公司
     */
    @SysLogAnnotation(value = "修改公司类型",userType = 2)
    @RequestMapping(method = RequestMethod.POST,value = "/web/find/commpany/update/by/type")
    public ServerResponse updateAppCompany(@RequestBody AppCompany appCompany){
        HashMap<String,Object> params = new  HashMap<String,Object>();
        params.put("type",1);
        //查询当前总公司
        AppCompany appCompany1 = appCompanyMapper.findCommpanyFourALL(params).get(0);
        if(appCompany.getCompanyId() == appCompany1.getCompanyId()){//判断要修改的是否就是总公司
            if(appCompany.getType() == 1){
                return ServerResponse.createBySuccess("保存成功");
            }else {
                return ServerResponse.createByErrorMessage("保存失败，至少需要一个总公司");
            }
        }else {//反之要修改的当前数据  不是总公司
            if(appCompany.getType() == 1){
                appCompanyMapper.updateType(appCompany);
                appCompany1.setType(2);
                appCompanyMapper.updateType(appCompany1);
                //刷新redis
                companyService.findtAppCompany(appCompany1.getCompanyId(), 0);
                return ServerResponse.createBySuccess("保存成功");
            }else {
                int i = appCompanyMapper.updateAppCompany(appCompany);
                //刷新redis
                companyService.findtAppCompany(appCompany.getCompanyId(), 0);
                return ServerResponse.createBySuccess("保存成功");
            }

        }

    }
    /**
     * 联盟  分佣  杀熟 三个list
     */
    @RequestMapping(method = RequestMethod.GET,value = "/web/find/commpany/three/list")
    public ServerResponse<HashMap<String,Object>> findThreeList(){
        HashMap<String,Object> map = new HashMap<String,Object>();
        List<TaobaoScheme> taoBaoPlanList;
        if(getAuthentication().getRoleId() == 0){
             taoBaoPlanList = taoBaoPlanService.findTaoBaoPlanAll(null);
        }else {
            HashMap<String,Object> hashMap = new HashMap<String,Object>();
            hashMap.put("companyId",getAuthentication().getCompanyId());
             taoBaoPlanList = taoBaoPlanService.findTaoBaoPlanAll(hashMap);
        }

        List<AppOrderFeeScheme> orderFeelist = appOrderfeeschemeService.selectAppOrderfeeschemeList(null);
        List<AppGeneralFeeScheme> generalFeeList = generalfeeschemeService.selectAppGeneralfeeschemeList(null);
        map.put("taoBaoPlanList",taoBaoPlanList);
        map.put("orderFeelist",orderFeelist);
        map.put("generalFeeList",generalFeeList);
        return  ServerResponse.createBySuccess(map);
    }

    //获取分公司邀请链接
    @RequestMapping(method = RequestMethod.GET,value = "/web/find/commpany/getInviteCodeUrl")
    public ServerResponse<HashMap<String,Object>> get(String companyId) {
        //public ServerResponse<String> get(String invitecode) {
        //AppCompany company = iAppCompanyService.findtAppCompanyInviteCode(invitecode);


        HashMap<String,Object> hashMap = new HashMap<>();hashMap.put("companyId",companyId);
        AppCompany data = (AppCompany) iAppCompanyService.findCommpany(hashMap).getData();
        String inviteCode = data.getInviteCode();


        String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid="+ WechatConfig.APPID+""
                + "&redirect_uri="+ WechatConfig.RETURNURL
                + "&response_type=code&scope=snsapi_userinfo"
                + "&state=invitecode:"+inviteCode+":"+companyId+"#wechat_redirect";
        String shorUrl = dwzService.getShorUrl(redirectUrl);//生成短连接诶
        hashMap.put("redirectUrl",redirectUrl);
        hashMap.put("shorUrl",shorUrl);
        return ServerResponse.createBySuccess(hashMap);

    }
}
